package query; /**
 * @Description
 * @Author maogen.ymg
 * @Date 2020/4/15 12:12
 */
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;

import java.io.File;
import java.io.IOException;

class Main extends Application {
    @Override
    public void start(final Stage stage) throws IOException {

        final WebView browser = new WebView();
        webEngine = browser.getEngine();
        String url = new File("visualize/test1.html").toURI().toURL().toString();
        webEngine.load(url);
        webEngine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState,
                 Worker.State newState) -> {

                    if (newState == Worker.State.SUCCEEDED) {
                        JSObject win = (JSObject) webEngine.executeScript("window");
                        win.setMember("apps",apps);//设置变量
                    }
                });

        Button button1 = new Button("java调JS方法");
        button1.setOnAction(event -> {
            try {

                JSObject win = (JSObject) webEngine.executeScript("window");
                //webEngine.executeScript("show()");//执行js函数
                //win.call("show","a","b");
                win.eval("show('a','b')");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        VBox stackPane = new VBox();
        stackPane.setSpacing(20);
        stackPane.getChildren().addAll(button1,browser);
        Scene scene = new Scene(stackPane,600,400);

        scene.setRoot(stackPane);
        stage.setScene(scene);
        stage.show();

    }

    A apps = new A();

    WebEngine webEngine;

    public static void main(String[] args) {
        launch(args);
    }

    //必须公有
    public static class A{

        public String showInfo(String info) {
            return "A{info="+ info +"}";
        }
    }
}